﻿@*
    采购单退货单管理页面
*@
@page "/buyorderreturn"
@using System.Collections.ObjectModel
@inject DialogService DialogService
@inject IBuyOrderReturnService BuyOrderReturnService

<RadzenText TextStyle="TextStyle.H4">退货单</RadzenText>
<PageTitle>退货单</PageTitle>
<RadzenStack Style="display: flex; margin: 0px 10px 10px 0px" Orientation="Orientation.Horizontal" JustifyContent="JustifyContent.Start" AlignItems="AlignItems.Center">
    <RadzenDatePicker @bind-Value=@startDatetime @onchange:preventDefault Name="RadzenDatePickerBindValue" ShowCalendarWeek />
    <RadzenDatePicker @bind-Value=@endDatetime @onchange:preventDefault Name="RadzenDatePickerBindValue" ShowCalendarWeek />
    <RadzenTextBox @bind-Value="@keyword" Placeholder="名称/手机号" Style="margin:10px 0px 10px 0px" />
    <RadzenButton Text="查询" Icon="refresh" @onclick:stopPropagation Click=@(args => Search()) ButtonStyle="ButtonStyle.Primary" />
    <RadzenButton Text="新增" Icon="add_circle" Click=@(args => Add()) ButtonStyle="ButtonStyle.Primary" />
</RadzenStack>

<RadzenDataGrid EmptyText="暂无数据"
                Data="@Data"
                @bind-Value=@selectedReturns
                GridLines="@Radzen.DataGridGridLines.Default"
                AllowPaging="true"
                AllowSorting="true"
                SelectionMode="DataGridSelectionMode.Single"
                FilterCaseSensitivity="FilterCaseSensitivity.CaseInsensitive">
    <Columns>
        <RadzenDataGridColumn Property="Id" Title="序号" Width="100px" TextAlign="TextAlign.Center" />
        <RadzenDataGridColumn Property="" Title="操作">
            <Template Context="data">
                <RadzenStack Gap="10" Style="margin-bottom: 10px" Orientation="Orientation.Horizontal">
                    <RadzenButton Text="修改" @onclick:stopPropagation Click="@(args => Update(data))" ButtonStyle="ButtonStyle.Primary" />
                    <RadzenButton Text="删除" @onclick:stopPropagation Click="@(args => Delete(data))" ButtonStyle="ButtonStyle.Danger" />
                </RadzenStack>
            </Template>
        </RadzenDataGridColumn>
        <RadzenDataGridColumn Property="Code" Title="退货单编号" />
        <RadzenDataGridColumn Property="Name" Title="退货单名称" />
        <RadzenDataGridColumn Property="BuyOrder.Code" Title="采购单编号" />
        <RadzenDataGridColumn Property="BuyOrder.Name" Title="采购单名称" />
        <RadzenDataGridColumn Property="Supplier.Name" Title="客户名称" />
        <RadzenDataGridColumn Property="CreatedAt" Title="创建时间">
            <Template Context="data">
                @data.CreatedAt.ToString("D")
            </Template>
        </RadzenDataGridColumn>
        <RadzenDataGridColumn Property="Remark" Title="备注" />
    </Columns>
</RadzenDataGrid>

<RadzenDataGrid Style="margin-top:15px;"
                EmptyText="暂无数据"
                Data="@details"
                GridLines="@Radzen.DataGridGridLines.Default"
                AllowPaging="true"
                AllowSorting="true"
                SelectionMode="DataGridSelectionMode.Single"
                FilterCaseSensitivity="FilterCaseSensitivity.CaseInsensitive">
    <Columns>
        <RadzenDataGridColumn Property="Id" Title="序号" Width="100px" TextAlign="TextAlign.Center" />
        <RadzenDataGridColumn Property="" Title="操作">
            <Template Context="data">
                <RadzenStack Gap="10" Orientation="Orientation.Horizontal">
                    <RadzenButton Text="删除" @onclick:stopPropagation Click="@(args => DeleteDetail(data))" ButtonStyle="ButtonStyle.Danger" />
                </RadzenStack>
            </Template>
        </RadzenDataGridColumn>
        <RadzenDataGridColumn Property="Product.Code" Title="产品编号" />
        <RadzenDataGridColumn Property="Product.Name" Title="名称" />
        <RadzenDataGridColumn Property="UnitPrice" Title="客户名称" />
        <RadzenDataGridColumn Property="TotalPrice" Title="合计" />
        <RadzenDataGridColumn Property="CreatedAt" Title="创建时间">
            <Template Context="data">
                @data.CreatedAt.ToString("D")
            </Template>
        </RadzenDataGridColumn>
        <RadzenDataGridColumn Property="Remark" Title="备注" />

    </Columns>
</RadzenDataGrid>

@code {
    IList<BuyOrderReturn> selectedReturns = new List<BuyOrderReturn>();

    private IList<BuyOrderReturnDetail> details {
        get 
        {
            return selectedReturns.Any() ? selectedReturns![0].Details : new List<BuyOrderReturnDetail>();            
        } 
    }
    private string keyword = string.Empty;
    private DateTime startDatetime { get; set; } = DateTime.Now;
    private DateTime endDatetime { get; set; } = DateTime.Now;
    ObservableCollection<BuyOrderReturn> Data = new ObservableCollection<BuyOrderReturn>();

    private void OnRowSelected(object order)
    {
        StateHasChanged();
    }

    private void Search()
    {
        var list = BuyOrderReturnService.Search(new BaseInput()
        {
            keyword = keyword,
            sdate = startDatetime,
            edate = endDatetime
        });
        Data = new ObservableCollection<BuyOrderReturn>(list);
    }

    private async void Add()
    {
        var order = new BuyOrderReturn();
        BuyOrderReturn result = await DialogService.OpenAsync<BuyOrderReturnAddDialog>(
            $"新增退货单",
            new Dictionary<string, object>() {{ "PReturn", order }},
            new DefaultDialogOptions(width: "1600px", height: "1312px"));

        if (result != null) Data!.Add(result);
    }

    private async void Update(BuyOrderReturn selectedItem)
    {
        BuyOrderReturn result = await DialogService.OpenAsync<BuyOrderReturnAddDialog>(
            $"修改退货单",
            new Dictionary<string, object>() {{ "PReturn", selectedItem }},
            new DefaultDialogOptions(width: "1600px", height: "1312px"));                      
        if (result != null)
        {
            StateHasChanged();
        }
    }
    private async void Delete(BuyOrderReturn selectedItem)
    {
        var result = await DialogService.Confirm("确认要删除吗?", "提示", new ConfirmOptions()
        {
            OkButtonText = "确定",
            CancelButtonText = "取消"
        });

        if ((bool)result)
        {
            try
            {
                BuyOrderReturnService.Delete(selectedItem.Id);
                Data!.Remove(selectedItem);
                if (Data.Count > 0)
                {
                    selectedReturns = new List<BuyOrderReturn>()
                    {
                        Data[0]
                    };
                }
                else
                {
                    selectedReturns = new List<BuyOrderReturn>();
                }
            }
            catch (Exception e)
            {
                await DialogService.Alert(e.Message, "错误", new AlertOptions() { OkButtonText = "确定" });
            }
        }
    }

    private async void DeleteDetail(BuyOrderReturnDetail detail)
    {
        var result = await DialogService.Confirm("确认要删除吗?", "提示", new ConfirmOptions()
        {
            OkButtonText = "确定",
            CancelButtonText = "取消"
        });

        if ((bool)result)
        {
            try
            {
                if (selectedReturns != null && selectedReturns.Count > 0)
                {
                    selectedReturns[0].Details.Remove(detail);
                }
            }
            catch (Exception e)
            {
                await DialogService.Alert(e.Message, "错误", new AlertOptions() { OkButtonText = "确定" });
            }
        }
    }

    protected override async Task OnInitializedAsync()
    {
        await base.OnInitializedAsync();

        var input = new BaseInput()
        {
            keyword = keyword,
            sdate = startDatetime,
            edate = endDatetime
        };
        var list = BuyOrderReturnService.Search(input);
        Data = new ObservableCollection<BuyOrderReturn>(list);
        if (Data.Count > 0)
        {
            selectedReturns = new List<BuyOrderReturn>()
            {
                Data[0]
            };
        }
    }

}
